package com.deeper.customview.ui.c4.demo.c04d10;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

import com.deeper.customview.R;

public class CirclePhotoView extends View {
    private static final String TAG = com.deeper.customview.ui.c4.exercise.c04e04.CirclePhotoView.class.getSimpleName();

    private Paint dstPaint;
    private Paint maskPaint;
    private Paint contentPaint;
    private Canvas contentCanvas;
    private Bitmap bmpHeader;
    private Bitmap contentBmp;
    private Bitmap maskBmp;
    private Canvas maskCanvas;
    private Bitmap dstBmp;
    private Canvas dstCanvas;
    private PorterDuffXfermode porterDuffXfermode;

    public CirclePhotoView(Context context) {
        super(context, null);
    }

    public CirclePhotoView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs, 0);
        initPaint();
    }

    public CirclePhotoView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private void initPaint() {
        contentPaint = new Paint();

        maskPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        maskPaint.setStyle(Paint.Style.FILL);

        dstPaint = new Paint();
        porterDuffXfermode = new PorterDuffXfermode(PorterDuff.Mode.DST_IN);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        bmpHeader = BitmapFactory.decodeResource(getResources(), R.mipmap.dog, null);

        if (contentBmp == null) {
            contentBmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
            contentCanvas = new Canvas(contentBmp);
        }

        if (maskBmp == null) {
            maskBmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
            maskCanvas = new Canvas(maskBmp);
        }

        if (dstBmp == null) {
            dstBmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
            dstCanvas = new Canvas(dstBmp);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        contentCanvas.drawBitmap(bmpHeader, 0, 0, contentPaint);
        maskCanvas.drawCircle(150, 150, 150, maskPaint);

        dstPaint.setXfermode(porterDuffXfermode);
        int layer = canvas.saveLayer(new RectF(0, 0, 300, 300), null);
        dstCanvas.drawBitmap(contentBmp, 0, 0, null);
        dstCanvas.drawBitmap(maskBmp, 0, 0, dstPaint);
        dstPaint.setXfermode(null);
        canvas.restoreToCount(layer);
        canvas.drawBitmap(dstBmp, 0, 0, dstPaint);
    }
}
